package bpm.dao.impl.document;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import bpm.dao.document.CommentDao;
import bpm.domain.document.Comment;
/**
 * 
 * @author ZhaoWangLong Sep 16, 2011
 *
 */
@Repository("commentDao")
public class CommentDaoImpl implements CommentDao {
	@Resource private JdbcTemplate jdbcTemplate;
	private final Logger logger=Logger.getLogger(CommentDaoImpl.class);
	public void delete(Comment comment) {
		String sql="delete from BPM_DC_COMMENT where COMMENT_ID= ?";
		this.jdbcTemplate.update(sql, new Object[]{comment.getCommentId()});
	}

	@SuppressWarnings("unchecked")
	public Comment getById(Comment comment) {
		String sql="select COMMENT_ID, CATEGORY_ID, CATEGORY_NAME, FIELD_KEY, FIELD_NAME,  "
			+"  RANK, CREATE_TIME, DESCRIPTION from BPM_DC_COMMENT where COMMENT_ID = ?";
		List<Comment> comments= this.jdbcTemplate.query(sql, new Object[]{comment.getCommentId()},
				new CommentRowMapper());
		if(comments!=null&&comments.size()>0){
			return comments.get(0);
		}
		return null;
	}

	public Integer getCount(String sql, Object... obj) {
		return this.jdbcTemplate.queryForInt(sql, obj);
	}

	@SuppressWarnings("unchecked")
	public List<Comment> getList(String sql, Object... obj) {
		return this.jdbcTemplate.query(sql, obj, new CommentRowMapper());
	}

	public void save(Comment comment) {
		logger.debug("Comment : "+comment);
		String sql="insert into BPM_DC_COMMENT (COMMENT_ID, CATEGORY_ID, CATEGORY_NAME, FIELD_KEY, FIELD_NAME," +
				" RANK, CREATE_TIME, DESCRIPTION ) values (?,?,?,?,?,?,?,?) ";
		this.jdbcTemplate.update(sql,new Object[]{
				comment.getCommentId(),comment.getCategory()==null?0:comment.getCategory().getId(),
				comment.getCategory()==null?null:comment.getCategory().getName(),
				comment.getField()==null?null:comment.getField().getKey(),
				comment.getField()==null?null:comment.getField().getName(),
			    comment.getRank(),comment.getCreateTime(),
				comment.getDescription()
		});
	}

	public void update(Comment comment) {
		logger.debug("Comment : "+comment);
		String sql=" update BPM_DC_COMMENT set CATEGORY_ID=?, CATEGORY_NAME=?, FIELD_KEY=?, FIELD_NAME=? ,"
			+" RANK=?,DESCRIPTION=? where COMMENT_ID=? ";
		this.jdbcTemplate.update(sql,new Object[]{
				comment.getCategory()==null?0:comment.getCategory().getId(),
				comment.getCategory()==null?null:comment.getCategory().getName(),
				comment.getField()==null?null:comment.getField().getKey(),
				comment.getField()==null?null:comment.getField().getName(),
				comment.getRank(),
				comment.getDescription(),comment.getCommentId()
		});
	}

}
